<template>
  <div class="icon-test-page">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>图标映射测试</span>
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索图标名称"
            style="width: 300px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <!-- 数据库图标映射展示 -->
      <el-divider content-position="left">数据库图标映射 ({{ filteredIcons.length }}个)</el-divider>
      <div class="icons-grid">
        <div 
          v-for="iconName in filteredIcons" 
          :key="iconName" 
          class="icon-item"
          @click="copyIconName(iconName)"
        >
          <div class="icon-display">
            <el-icon :size="24">
              <component :is="getIconComponent(iconName)" />
            </el-icon>
          </div>
          <div class="icon-info">
            <div class="icon-name">{{ iconName }}</div>
            <div class="icon-component">{{ getIconComponent(iconName) }}</div>
          </div>
        </div>
      </div>

      <!-- 使用示例 -->
      <el-divider content-position="left">使用示例</el-divider>
      <div class="usage-examples">
        <el-alert
          title="图标使用说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>1. 数据库中保存图标名称（如：setting、user、team）</p>
            <p>2. 前端通过 getIconComponent() 函数映射到 Element Plus 图标组件</p>
            <p>3. 点击图标可复制图标名称到剪贴板</p>
          </template>
        </el-alert>

        <div class="code-examples">
          <h4>代码示例：</h4>
          <el-tabs>
            <el-tab-pane label="Vue模板">
              <pre><code>&lt;el-icon&gt;
  &lt;component :is="getIconComponent('{{ selectedIcon || 'setting' }}')" /&gt;
&lt;/el-icon&gt;</code></pre>
            </el-tab-pane>
            <el-tab-pane label="数据库插入">
              <pre><code>INSERT INTO permission (name, code, icon) VALUES 
('系统管理', 'system:manage', '{{ selectedIcon || 'setting' }}');</code></pre>
            </el-tab-pane>
            <el-tab-pane label="JavaScript">
              <pre><code>import { getIconComponent } from '@/utils/iconMap'

const iconComponent = getIconComponent('{{ selectedIcon || 'setting' }}')</code></pre>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 缺失图标检测 -->
      <el-divider content-position="left">图标检测</el-divider>
      <div class="icon-detection">
        <el-space>
          <el-button @click="testDatabaseIcons" :loading="testing">
            检测数据库图标
          </el-button>
          <el-button @click="showMissingIcons" type="warning">
            显示缺失图标
          </el-button>
          <el-button @click="addNewIcon" type="success">
            添加新图标映射
          </el-button>
        </el-space>

        <div v-if="missingIcons.length > 0" class="missing-icons">
          <el-alert
            title="发现缺失的图标映射"
            type="warning"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>以下图标名称在数据库中使用但未在前端映射：</p>
              <el-tag 
                v-for="icon in missingIcons" 
                :key="icon" 
                type="warning"
                class="missing-icon-tag"
              >
                {{ icon }}
              </el-tag>
            </template>
          </el-alert>
        </div>
      </div>

      <!-- 新增图标映射对话框 -->
      <el-dialog
        v-model="showAddDialog"
        title="添加图标映射"
        width="500px"
      >
        <el-form :model="newIconForm" label-width="120px">
          <el-form-item label="数据库图标名">
            <el-input v-model="newIconForm.dbName" placeholder="如：new-icon" />
          </el-form-item>
          <el-form-item label="Element图标名">
            <el-input v-model="newIconForm.elementName" placeholder="如：NewIcon" />
          </el-form-item>
          <el-form-item label="预览">
            <div class="icon-preview">
              <el-icon :size="32" v-if="newIconForm.elementName">
                <component :is="newIconForm.elementName" />
              </el-icon>
              <span v-else>请输入图标名称</span>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addIconMapping">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getIconComponent } from '@/utils/iconMap'

const searchKeyword = ref('')
const testing = ref(false)
const selectedIcon = ref('setting')
const missingIcons = ref([])
const showAddDialog = ref(false)

const newIconForm = ref({
  dbName: '',
  elementName: ''
})

// 数据库中使用的图标名称（从init_menu.sql提取）
const databaseIcons = [
  'setting', 'user', 'team', 'safety-certificate', 'apartment', 
  'user-switch', 'key', 'control', 'usergroup-add', 'dashboard',
  'user-circle', 'menu', 'house', 'document', 'folder', 'edit',
  'delete', 'view', 'plus', 'search', 'refresh', 'download',
  'upload', 'tools', 'monitor'
]

// 过滤图标
const filteredIcons = computed(() => {
  if (!searchKeyword.value) {
    return databaseIcons
  }
  return databaseIcons.filter(icon => 
    icon.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 复制图标名称
const copyIconName = async (iconName) => {
  try {
    await navigator.clipboard.writeText(iconName)
    selectedIcon.value = iconName
    ElMessage.success(`已复制图标名称: ${iconName}`)
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 测试数据库图标
const testDatabaseIcons = () => {
  testing.value = true
  
  const results = databaseIcons.map(iconName => {
    const component = getIconComponent(iconName)
    return {
      iconName,
      component,
      exists: component !== 'Document'
    }
  })
  
  const missing = results.filter(r => !r.exists).map(r => r.iconName)
  const existing = results.filter(r => r.exists).length
  
  console.log('图标检测结果:', results)
  
  ElMessage.success(`检测完成：${existing}个图标正常，${missing.length}个图标缺失`)
  
  if (missing.length > 0) {
    missingIcons.value = missing
  }
  
  testing.value = false
}

// 显示缺失图标
const showMissingIcons = () => {
  const missing = databaseIcons.filter(iconName => {
    const component = getIconComponent(iconName)
    return component === 'Document'
  })
  
  missingIcons.value = missing
  
  if (missing.length === 0) {
    ElMessage.success('所有图标映射都正常！')
  } else {
    ElMessage.warning(`发现 ${missing.length} 个缺失的图标映射`)
  }
}

// 添加新图标映射
const addNewIcon = () => {
  showAddDialog.value = true
  newIconForm.value = {
    dbName: '',
    elementName: ''
  }
}

// 确认添加图标映射
const addIconMapping = () => {
  const { dbName, elementName } = newIconForm.value
  
  if (!dbName || !elementName) {
    ElMessage.error('请填写完整的图标映射信息')
    return
  }
  
  // 这里可以添加到图标映射文件中
  ElMessage.info('请手动将以下映射添加到 src/utils/iconMap.js 文件中：')
  console.log(`'${dbName}': '${elementName}',`)
  
  showAddDialog.value = false
}
</script>

<style scoped>
.icon-test-page {
  padding: 20px;
}

.test-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icons-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin: 20px 0;
}

.icon-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.icon-display {
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: #f5f7fa;
  border-radius: 6px;
}

.icon-info {
  flex: 1;
}

.icon-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.icon-component {
  font-size: 12px;
  color: #666;
  font-family: 'Courier New', monospace;
}

.usage-examples {
  margin: 20px 0;
}

.code-examples {
  margin-top: 20px;
}

.code-examples pre {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.icon-detection {
  margin: 20px 0;
}

.missing-icons {
  margin-top: 16px;
}

.missing-icon-tag {
  margin: 4px;
}

.icon-preview {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

h4 {
  margin: 16px 0 8px 0;
  color: #333;
}
</style>